<template>
  <div v-if="homeBg" w-full h-screen box-border>
    <img :src="homeBg" w-full h-full alt="" />
    <shouhuan />
  </div>

  <screen-saver v-if="isOpenScrrenSaver" :visible="showScreenSaver" @close="closeScreenSaver" />
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { throttle } from 'lodash-es'
import { useConfigStore } from '@/store/modules/config'
// 导入屏保组件
import screenSaver from '@/components/screen-saver/index.vue'
// 手环组件
import shouhuan from '@/components/shouhuan/index.vue'

const router = useRouter()
let socket = null
// 状态管理
const configStore = useConfigStore()
const standbyTime = configStore.config?.standbyTime || 60000
// const curTopic = configStore.topics
const curTopic = computed(() => configStore.topics)
console.log("curTopic",curTopic.value)
const showScreenSaver = ref(false)
let screenSaverTimer = null
const isOpenScrrenSaver = ref(false)
const wsUrl = ref('ws://127.0.0.1:9094/ws')

// const homeBg = ref(curTopic.homeBg)
const homeBg = computed(() => curTopic.value.homeBg)


// 屏保相关方法
const resetHomeTimer = () => {
  if (!isOpenScrrenSaver.value) return

  clearTimeout(screenSaverTimer)
  screenSaverTimer = setTimeout(() => {
    console.log('开启屏保')
    showScreenSaver.value = true
  }, standbyTime)
}

const closeScreenSaver = () => {
  console.log('关闭屏保')
  showScreenSaver.value = false
  resetHomeTimer()
}


// 跳转搜索页
function toSearch(no) {
  if (showScreenSaver.value) {
    closeScreenSaver()
    setTimeout(() => {
      router.push({ path: '/search', query: { no: no } })
    }, 300)
    return
  }

  router.push({ path: '/search', query: { no: no } })
}

const handleMessage = throttle((event) => {
  try {
    console.log('收到WebSocket消息:', event.data)
    
    if (event.data) {
      toSearch(event.data)
    }
  } catch (e) {
    console.error('WebSocket消息解析失败:', e)
  }
}, 3000) // 3秒节流

// 初始化WebSocket
function initWebSocket() {
  socket = new WebSocket(wsUrl.value)

  socket.onopen = () => {
    console.log('WebSocket连接已建立')
  }

  socket.onmessage = handleMessage

  socket.onerror = (error) => {
    console.error('WebSocket错误:', error)
  }

  socket.onclose = () => {
    console.log('WebSocket连接已关闭')
  }
}

// 关闭WebSocket
function closeWebSocket() {
  if (socket && socket.readyState === WebSocket.OPEN) {
    socket.close()
  }
}

// 直接显示待机组件
function showStandby() {
  if (configStore.autoReback) { // 是否自动返回
    configStore.init()
    showScreenSaver.value = true
    configStore.setReback(false)
    
  }
}

// 生命周期钩子
onMounted(() => {
  // showStandby()
  configStore.init()
  isOpenScrrenSaver.value = true
  initWebSocket()
  if (screenSaverTimer) {
    clearTimeout(screenSaverTimer)
  }
  resetHomeTimer()
  document.addEventListener('touchstart', resetHomeTimer)
})

onUnmounted(() => {
  isOpenScrrenSaver.value = false
  document.removeEventListener('touchstart', resetHomeTimer)
  clearTimeout(screenSaverTimer)
  closeWebSocket()
})
</script>

<style scoped></style>
